package com.qf.commons.redis.utils;

import com.qf.commons.core.utils.ApplicationUtils;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

/**
 * author Ken
 * create_time 2022/11/23
 */
@Slf4j
public class MyLock {

    private static RedissonClient redissonClient;

    static {
        //通过工具方法，从IOC容器中获取执行类型的Bean（非注入的方式）
        redissonClient = ApplicationUtils.getBean(RedissonClient.class);
        System.out.println("手动获取Bean对象：" + redissonClient);
    }

    private static ThreadLocal<RLock> lockThreadLocal = new ThreadLocal<>();

    /**
     * 加锁的方法
     */
    public static void lock(String keyName){
        log.debug("[add lock] 尝试添加分布式锁 - {}", keyName);
        RLock lock = redissonClient.getLock(keyName);
        //阻塞式的获取分布式锁，一直等到获得分布式锁为止
        lock.lock();
        lockThreadLocal.set(lock);
        log.debug("[add lock] 获得分布式锁 - {}", keyName);
    }

    /**
     * 解锁的方法
     */
    public static void unlock(){
        RLock rLock = lockThreadLocal.get();
        if (rLock != null && rLock.isLocked()) {
            log.debug("[unlock] 解除分布式锁 - {}", rLock.getName());
            rLock.unlock();
            //清空ThreadLocal -
            lockThreadLocal.remove();
        }
    }
}
